package com.hmdp.utils;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.hmdp.dto.UserDTO;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import static com.hmdp.utils.RedisConstants.LOGIN_USER_KEY;
import static com.hmdp.utils.RedisConstants.LOGIN_USER_TTL;

public class RefreshTokenInterceptor implements HandlerInterceptor {
    private StringRedisTemplate stringRedisTemplate;
    //这里不能用依赖注入，是因为这个类不是spring管理的类，无法自动注入，
    // 拦截器是轻量级的，如果给他加上@Component注解，会增加开销
    public RefreshTokenInterceptor(StringRedisTemplate stringRedisTemplate) {
        this.stringRedisTemplate = stringRedisTemplate;
    }
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //1.获取session/token
//        HttpSession session = request.getSession();
        UserHolder.removeUser();
        String token = request.getHeader("authorization");
        if(StringUtils.isBlank(token)){
            //不存在直接放行
           return true;
        }
        //2.获取session/redis中的用户
//        UserDTO user =(UserDTO) session.getAttribute("user");
        Map<Object, Object> map = stringRedisTemplate.opsForHash().entries(LOGIN_USER_KEY + token);
        //3.判断用户是否存在
        if (map.isEmpty()){
            //不存在直接放行
            return true;
        }

        //4.将用户信息封装到UserDTO中
        UserDTO user = BeanUtil.fillBeanWithMap(map, new UserDTO(), false);


        //5.存在则保存用户信息到ThreadLocal
        UserHolder.saveUser(user);

        //6.刷新token的过期时间
        stringRedisTemplate.expire(LOGIN_USER_KEY+token,LOGIN_USER_TTL, TimeUnit.MINUTES);
        //7.放行
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        HandlerInterceptor.super.afterCompletion(request, response, handler, ex);
    }
}
